﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using FluentFTP;
using System.Net;
using LogLib;

namespace FTPService
{
    public class FtpDownload
    {
        private string _error = "";
        public string ErrorMessage
        {
            get
            {
                return _error;
            }
        }

        public bool Inited
        {
            get;
            private set;
        }

        public bool Closed
        {
            get;
            private set;
        }

        private FTPDownloadOption _option = new FTPDownloadOption();

        private void LoadSettings()
        {
            if (!File.Exists(_option.ConfigFilePath))
            {
                _option.Save();
            }
            else
            {
                _option.Load();
            }
        }

        public FtpDownload()
        {
            Inited = false;
            Closed = false;
            LoadSettings();
        }

        public FtpDownload(FTPDownloadOption opt)
        {
            Inited = false;
            Closed = false;
            _option = opt;
        }

         public bool Connect()
         {
             using (FtpClient conn = new FtpClient())
             {
                 conn.Host = _option.IP;
                 conn.Port = _option.Port;
                 conn.EncryptionMode = (FtpEncryptionMode)(int)_option.EncryptionMode;
                 conn.Credentials = new NetworkCredential(_option.User, _option.GetPassword());
                 try
                 {
                     conn.Connect();
                     Log.WriteAsync("FTP服务器连接成功!");
                     Inited = true;
                     conn.Disconnect();
                     return true;
                 }
                 catch (TimeoutException)
                 {
                     _error = "连接FTP服务器超时!\n请检查主机Host等配置是否正确。";
                     Log.WriteAsync(_error);
                     Inited = false;
                     return false;
                 }
                 catch (Exception ex)
                 {
                     _error = string.Format("连接FTP服务器失败.\n详情:{0}", ex.Message);
                     Log.WriteException(ex.ToString());
                     Log.WriteAsync(_error);
                     Inited = false;
                     return false;
                 }
             }
         }

         public bool Login(string inParam, out string outParam)
         {
             outParam = "";
             Log.AddBeginningBoundary();
             return Connect();
         }

         public void Logout()
         {
             if (!Inited)
             {
                 return;
             }
             Closed = true;
             Log.AddEndingBoundary();
         }

         public bool DownloadFile(string localPath, string remotePath,out string err)
         {
             bool isOK=false;
             err = "";
             using (FtpClient conn = new FtpClient())
             {
                 conn.Host = _option.IP;
                 conn.Port = _option.Port;
                 conn.EncryptionMode = (FtpEncryptionMode)(int)_option.EncryptionMode;
                 
                 conn.Credentials = new NetworkCredential(_option.User, _option.GetPassword());
                 try
                 {
                     conn.Connect();
                     conn.DownloadFile(localPath, remotePath, FtpLocalExists.Overwrite,
                         _option.NeedVerify ? FtpVerify.Retry : FtpVerify.None);
                     conn.Disconnect();
                     string strLog = string.Format("FTP文件{0}下在至{1}{2}成功!", remotePath, _option.IP, remotePath);
                     Log.WriteAsync(strLog);
                     isOK = true;
                 }
                 catch (TimeoutException ex)
                 {
                     err = "连接FTP服务器超时!\n请检查主机Host等配置是否正确。";
                     Log.WriteException(ex.ToString());
                     isOK = false;
                 }
                 catch (Exception ex){
                     err = string.Format("上传文件至ftp:/{0}{1}失败! \n异常详情:{2}\n{3}",
                         _option.IP,
                         remotePath,
                         ex.Message,
                         ex.InnerException);
                     Log.WriteException(ex.ToString());
                     isOK = false;
                 }
             }
             return isOK;
         }
    }
}
